<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/7
 * Time: 16:21
 */

namespace App\Task;


use EasySwoole\EasySwoole\Swoole\Task\AbstractAsyncTask;
use App\Enums\UrlEnums;
use EasySwoole\MysqliPool\Mysql;
use App\Library\Auth;
use EasySwoole\HttpClient\HttpClient;

class TeamInfoTask extends AbstractAsyncTask
{
    protected function run($taskData, $taskId, $fromWorkerId, $flags = null)
    {
        $team_id = $taskData['team_id'];
        $teamInfoUrl = UrlEnums::FJURL.UrlEnums::LOL_TEAM_INFO_PATH.'?team_id='.$team_id.'&version=2';
        $teamInfo = new HttpClient($teamInfoUrl);
        list($s1, $s2) = explode(' ', microtime());
        $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
        $option = [
            'path' => UrlEnums::LOL_TEAM_INFO_PATH,
            'api_time'  => $microtime
        ];
        $header = Auth::getInstance($option)->header();
        $teamInfo->setHeaders($header,true,false);
        $response = $teamInfo->get();
        $data = $response->getBody();
        $data = json_decode($data,true);

        $db = Mysql::defer('mysql');
        $player_ids = $db->where('team_id',$team_id)->getColumn('siam_team_player','player_id');

        if( empty($data['data']['players']) || $data['code'] != 200 ){
            return false;
        }

        foreach ( $data['data']['players'] as $k=>$v ){
            $data['data']['players'][$k]['game'] = 'lol';
        }

        if( !empty($player_ids) ){
            foreach ( $data['data']['players'] as $item ){
                if( in_array($item['player_id'],$player_ids) ){
                    $db->where('player_id',$item['player_id'])->where('game','lol')->update('siam_team_player',[
                        'team_id'   => $item['team_id'],
                        'avatar'    => $item['avatar'],
                        'nick_name' => $item['nick_name'],
                        'real_name' => $item['real_name'],
                        'position'  => $item['position'],
                        'country'   => $item['country'],
                        'introduction' => $item['introduction']
                    ]);
                }
            }
        }else{
            if( !empty($data['data']['players']) ){
                $db->insertMulti('siam_team_player',$data['data']['players']);
            }
        }
        return true;
    }

    public function finish($result, $task_id)
    {
        // TODO: Implement finish() method.
    }
}